package com.xzq.wanandroid.model;

import android.annotation.SuppressLint;
import android.os.Build;

import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.NetworkUtils;
import com.xzq.wanandroid.base.modle.BaseModle;
import com.xzq.wanandroid.base.utils.Constant;
import com.xzq.wanandroid.bean.db.Article;
import com.xzq.wanandroid.bean.db.Banner;
import com.xzq.wanandroid.contract.home.HomeContract;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;


/**
 * @ClassName : HomeModel
 * @Description : 封装本地的网络请求，并将数据缓存到本地
 * @Author : xzq
 * @Date: 2021-05-17 16:15
 * @Version :
 */
public class HomeModel extends BaseModle implements HomeContract.IHomeModel {

    public HomeModel() {
        setCookies(true);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public Observable<List<Banner>> loadBanner() {
        Observable<List<Banner>> loadFromLocal = Observable.create(emitter -> {
            List<Banner> bannerList = LitePal.findAll(Banner.class);
            emitter.onNext(bannerList);
            emitter.onComplete();
        });
        if (NetworkUtils.isConnected()) {
            Observable<List<Banner>> loadFromNet = loadBannerFromNet();
            return Observable.concat(loadFromLocal, loadFromNet);
        } else {
            return loadFromLocal;
        }
    }

    /**
     * 加载数据刷新Banner
     *
     * @return
     */

    @SuppressLint("NewApi")
    private Observable<List<Banner>> loadBannerFromNet() {
        return apiService.loadBanner().filter(bannerBean -> bannerBean.getErrorCode() == Constant.SUCCESS).
                map(bannerBean -> {
                    List<Banner> bannerList = new ArrayList<>();
                    bannerBean.getData().stream().forEach(
                            data -> {
                                Banner bannerDB = new Banner();
                                bannerDB.url = data.getUrl();
                                bannerDB.title = data.getTitle();
                                bannerDB.imagePath = data.getImagePath();
                                bannerDB.id = data.getId();
                                bannerList.add(bannerDB);
                            });
                    if (bannerList.size() > 0) {
                        LitePal.deleteAll(Banner.class);
                    }
                    LitePal.saveAll(bannerList);
                    return bannerList;
                });
    }

    @Override
    public Observable<List<Banner>> refreshBanner() {
        return loadBannerFromNet();
    }

    @Override
    public Observable<List<Article>> loadArticle(int pageNum) {
        Observable<List<Article>> loadFromNet=loadArticleFromNet(pageNum);
        return loadFromNet;
    }


    /**
     * 加载网络数据
     * @param pageNum
     * @return
     */
    @SuppressLint("NewApi")
    private Observable<List<Article>> loadArticleFromNet(int pageNum) {
        return apiService.loadArtical(pageNum).filter(articalBean -> articalBean.getErrorCode()==Constant.SUCCESS)
                .map(articalBean -> {
                List<Article> articleList=new ArrayList<>();
                    articalBean.getData()
                            .getDatas().stream().forEach(datasBean -> {
                        Article articleDB = new Article();
                        articleDB.type = Article.TYPE_HOME;
                        articleDB.articleId = datasBean.getId();
                        articleDB.title = datasBean.getTitle();
                        articleDB.author = datasBean.getAuthor();
                        articleDB.chapterName = datasBean.getChapterName();
                        articleDB.superChapterName = datasBean.getSuperChapterName();
                        articleDB.time = datasBean.getPublishTime();
                        articleDB.link = datasBean.getLink();
                        articleDB.collect = datasBean.isCollect();
                        articleDB.niceDate = datasBean.getNiceDate();
                        articleDB.shareUser = datasBean.getShareUser();
                        articleDB.isFresh = datasBean.isFresh();
                        articleDB.isTop = false;
                        articleList.add(articleDB);
                    });
                    return articleList;
                });
    }

    @Override
    public Observable<List<Article>> refreshArticle(int pageNum) {
        return loadArticleFromNet(pageNum);
    }

    @Override
    public Observable<List<Article>> loadTopArticle() {
      Observable<List<Article>> loadFromNet=loadTopArticleFromNet();
        return loadFromNet;
    }

    @Override
    public Observable<List<Article>> refreshTopArticle() {
        return loadTopArticleFromNet();
    }

    @SuppressLint("NewApi")
    private Observable<List<Article>> loadTopArticleFromNet() {
        return apiService.loadTopArtical().filter(topArticalBean ->topArticalBean.getErrorCode()==Constant.SUCCESS)
                .map(topArticalBean -> {
                  List<Article> topArticleList=new ArrayList<>();
                  topArticalBean.getData().stream().forEach(datasBean -> {
                   Article article=new Article();
                      article.type = Article.TYPE_TOP;
                      article.articleId = datasBean.getId();
                      article.title = datasBean.getTitle();
                      article.author = datasBean.getAuthor();
                      article.chapterName = datasBean.getChapterName();
                      article.superChapterName = datasBean.getSuperChapterName();
                      article.time = datasBean.getPublishTime();
                      article.link = datasBean.getLink();
                      article.collect = datasBean.isCollect();
                      article.niceDate = datasBean.getNiceDate();
                      article.shareUser = datasBean.getShareUser();
                      article.isFresh = datasBean.isFresh();
                      article.isTop = true;
                      if (article.superChapterName.equals("问答")) {
                          article.isQuestion = true;
                      }
                      topArticleList.add(article);
                  } );
                  return topArticleList;
                });
    }
}


